﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;


namespace Comm.PublicClass
{
    public class MyConvert
    {


        /// <summary>
        /// 字符转ASCII码
        /// </summary>
        /// <param name="character">字符</param>
        /// <returns>字符对应的ASCII码</returns>
        public static int ChrToASCII(char character) //ord   string character
        {

            // if (character.Length == 1)
            // {
            try
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character.ToString())[0];
                return intAsciiCode;
            }
            catch (Exception ex)
            {
                return -1;

            }

            //  }
            // else
            //  {
            //     return -1;
            //      //throw new Exception("Character is not valid.");
            //  }

        }

        /// <summary>
        /// ASCII码转字符
        /// </summary>
        /// <param name="asciiCode">ASCII码</param>
        /// <returns>转换后的字符</returns>
        public static string ASCIIToChr(int asciiCode)  //chr
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                return null;  //throw new Exception("ASCII Code is not valid.");
            }
        }

        /// <summary>
        /// 十六进制字符串转ASCII
        /// </summary>
        /// <param name="Msg">十六进制字符串</param>
        /// <returns>用ASCII表示的字符串</returns>
        public static string HexToASCII(string Msg)
        {
            //调用下面转字节数组
            //byte[] buff = new byte[Msg.Length / 2];
            //string Message = "";
            //for (int i = 0; i < buff.Length; i++)
            //{
            //    buff[i] = byte.Parse(Msg.Substring(i * 2, 2),
            //       System.Globalization.NumberStyles.HexNumber);
            //}
            try
            {
                byte[] buff = HexStringToByteArray(Msg);
                System.Text.Encoding chs = System.Text.Encoding.ASCII;
                return chs.GetString(buff);
            }
            catch (Exception ex)
            {
                return null;

            }

        }


        /// <summary>
        /// 十六进制转ASCII 可转中文
        /// </summary>
        /// <param name="Msg">十六进制字符串</param>
        /// <returns>用ASCII表示的字符串</returns>
        public static string HexToStr(string Msg)
        {

            try
            {
                byte[] buff = HexStringToByteArray(Msg);

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                System.Text.Encoding chs = System.Text.Encoding.GetEncoding("GB2312");
                return chs.GetString(buff);
            }
            catch (Exception ex)
            {
                return null;

            }

        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="Msg">需转换的字符串</param>
        /// <returns>十六进制字符串</returns>
        public static string StrToHex(string Msg)
        {
            try
            {
                if (string.IsNullOrEmpty(Msg))
                    Msg = "0";

                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Msg);
                string str = "";
                for (int i = 0; i < bytes.Length; i++)
                {
                    str += string.Format("{0:X}", bytes[i]);
                }
                return str;
            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>
        /// 十六进制转换为十进制
        /// </summary>
        /// <param name="x">十六进制字符串</param>
        /// <returns></returns>
        public static string HexToDec(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x))
                    x = "0";
                return Convert.ToInt32(x, 16).ToString();
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// 十六进制转换为二进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string HexToBin(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x))
                    x = "0";
                StringBuilder strb = new StringBuilder();
                byte[] t = HexStringToByteArray(x);
                for (int i = 0; i < t.Length; i++)
                {
                    strb.Append(Convert.ToString(t[i], 2).PadLeft(8, '0'));
                }
                return strb.ToString();
                //int values = Convert.ToInt32(x.Substring(0, 8), 16);
                //return Convert.ToString(values, 2);
            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>
        /// 十六进制转换为浮点型
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static float HexToFloat(string x)
        {
            //try
            //{
            if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                x = "0";

            StringBuilder strb = new StringBuilder();
            byte[] t = HexStringToByteArray(x);
            float fvalue = BitConverter.ToSingle(t, 0);
            return fvalue;
            //}
            //catch (Exception ex)
            //{
            //    return 0;

            //}
        }

        /// <summary>
        /// 十六进制转换为浮点型
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string FloatToHex(float fvalue)
        {
            try
            {

                byte[] bytes = BitConverter.GetBytes(fvalue);
                string str = ByteArrayToHexString(bytes, 8);
                return str;
            }
            catch
            {
                return null;

            }
        }

        /// <summary>
        /// 十六进制转换为浮点型
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string FloatToHex(string strvalue)
        {
            try
            {
                if (string.IsNullOrEmpty(strvalue)) //hxh 2018-8-22 如果传进来为空可以返回0
                    strvalue = "0";
                float fvalue = float.Parse(strvalue);
                string str = FloatToHex(fvalue);
                return str;
            }
            catch
            {
                return null;

            }
        }


        /// <summary>
        /// 十六进制转换字节数组
        /// </summary>
        /// <param name="s">十六进制字符串</param>
        /// <returns>转换后的字节数组</returns>
        public static byte[] HexStringToByteArray(string s)
        {
            try
            {
                if (string.IsNullOrEmpty(s)) //hxh 2018-8-22 如果传进来为空可以返回0
                    s = "0";
                s = s.Replace(" ", "");
                s = s.Length % 2 > 0 ? "0" + s : s;
                byte[] buffer = new byte[s.Length / 2];
                for (int i = 0; i < s.Length; i += 2)
                    buffer[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);

                return buffer;
            }
            catch (Exception ex)
            {

                return null;
            }
        }


        /// <summary>
        /// 十六进制转换字节数组
        /// </summary>
        /// <param name="s">十六进制字符串</param>
        /// <returns>转换后的字节数组</returns>
        public static byte[] HexStringToByteArray(string s, ref string errinfo)
        {
            try
            {
                if (!PubFunction.IsHexStr(s))
                {
                    errinfo = "invalid character";
                    return null;
                }
                byte[] buffer = HexStringToByteArray(s);
                return buffer;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                return null;
            }
        }


        /// <summary>
        /// 十六进制转换字符数组
        /// </summary>
        /// <param name="s">十六进制字符串</param>
        /// <returns>转换后的字符数组</returns>
        public static char[] HexStringToCharArray(string s)
        {
            try
            {
                if (string.IsNullOrEmpty(s)) //hxh 2018-8-22 如果传进来为空可以返回0
                    s = "0";
                s = s.Replace(" ", "");
                s = s.Length % 2 > 0 ? "0" + s : s;
                char[] buffer = new char[s.Length / 2];
                for (int i = 0; i < s.Length; i += 2)
                {
                    byte tmpbyte = Convert.ToByte(s.Substring(i, 2), 16);
                    buffer[i / 2] = Convert.ToChar(tmpbyte);
                }
                return buffer;
            }
            catch (Exception ex)
            {

                return null;
            }
        }



        /// <summary>
        /// 字节数组转换十六进制
        /// </summary>
        /// <param name="data">字节数组</param>
        /// <returns>转换后的字符串</returns>
        public static string ByteArrayToHexString(byte[] data)
        {
            try
            {
                StringBuilder sb = new StringBuilder(data.Length * 2);
                foreach (byte b in data)
                    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
                return sb.ToString().ToUpper();
            }
            catch (Exception ex)
            {

                return null;
            }
        }


        /// <summary>
        ///字节数组中一定数量的元素转换十六进制字符串 
        /// </summary>
        /// <param name="data">字节数组</param>
        /// <param name="datalength">需转换的元素个数</param>
        /// <returns>转换后的字符串</returns>
        public static string ByteArrayToHexString(byte[] data, int datalength)
        {
            try
            {
                StringBuilder sb = new StringBuilder(datalength * 2);
                if (data.Length < datalength)
                {
                    datalength = data.Length;
                }
                for (int i = 0; i < datalength; i++)
                {
                    byte b = data[i];
                    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
                }
                return sb.ToString().ToUpper();
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 十进制转换为二进制
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <returns>二进制表示的等值字符串</returns>
        public static string DecToBin(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    x = "0";
                int values = Convert.ToInt32(x);
                return Convert.ToString(values, 2);
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>         
        ///  十进制转换为二进制,定长转换
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <param name="iLength">长度参数</param>
        /// <returns>一定条度的二进制表示的等值字符串</returns>
        public static string DecToBin(string x, int iLength)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    x = "0";
                long values = Convert.ToInt64(x);
                string str = Convert.ToString(values, 2);
                str = str.PadLeft(iLength, '0');
                return str;
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// 十进制转换为十六进制，转出长度自动用0补成偶数位
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <returns>十六进制表示的等值字符串</returns>
        public static string DecToHex(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    x = "0";

                long values = Convert.ToInt64(x);
                string str = Convert.ToString(values, 16);
                //加判断长度奇偶，奇数时补零

                if (str.Length % 2 != 0)
                    str = '0' + str;
                return str.ToUpper();
            }
            catch (Exception ex)
            {
                return null;

            }


        }

        /// <summary>
        /// 十进制转换为十六进制
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <param name="bFillZero">是否补零成偶数位</param>
        /// <returns>十六进制表示的等值字符串</returns>        
        public static string DecToHex(string x, bool bFillZero)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    return "0";

                long values = Convert.ToInt64(x);
                string str = Convert.ToString(values, 16);
                //加判断长度奇偶，奇数时补零
                if (bFillZero && str.Length % 2 != 0)
                    str = '0' + str;

                return str.ToUpper();
            }
            catch (Exception ex)
            {
                return null;

            }


        }

        /// <summary>
        /// 十进制转换为十六进制，且规定转换后字符串长度
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <param name="iLength">十六进制字符长度</param>
        /// <returns>一定长度的十六进制字符串</returns>
        public static string DecToHex(string x, int iLength)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    return "0".PadLeft(iLength, '0');

                long values = Convert.ToInt64(x);
                string str = Convert.ToString(values, 16);
                if (iLength > 0 && str.Length > iLength)
                {
                    str = str.Substring(str.Length - iLength);
                }
                else
                    str = str.PadLeft(iLength, '0');
                return str.ToUpper();
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// hxh 2018-11-12 不定长十进制转换为十六进制，且规定转换后字符串长度
        /// </summary>
        /// <param name="x">十进制字符串</param>
        /// <param name="iLength">十六进制字符长度</param>
        /// <returns>一定长度的十六进制字符串</returns>
        public static string RandomDecToHex(string str, int iLength)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) //如果传进来为空可以返回0
                    return "0".PadLeft(iLength, '0');

                int[] input = new int[50];
                int[] output = new int[100];

                int len = str.Length;
                for (int i = 0; i < len; i++)
                {
                    input[i] = str[i] - '0';
                }
                int sum = 1, d = 0, k = 0;
                while (sum > 0)
                {
                    sum = 0;
                    for (int i = 0; i < len; i++)
                    {
                        d = input[i] / 2;
                        sum += d;
                        if (i == (len - 1))
                        {
                            output[k++] = input[i] % 2;
                        }
                        else
                            input[i + 1] += (input[i] % 2) * 10;
                        input[i] = d;
                    }
                }
                string binstr = "";
                for (int j = 0; j < k; j++)
                {
                    binstr = output[j].ToString() + binstr;
                }

                string hexstr = "";
                while (binstr.Length > 0)
                {
                    if (binstr.Length > 8)
                    {
                        hexstr = BinToHex(binstr.Substring(binstr.Length - 8, 8), 2) + hexstr;
                        binstr = binstr.Substring(0, binstr.Length - 8);
                    }
                    else
                    {
                        hexstr = BinToHex(binstr, 2) + hexstr;
                        binstr = "";
                    }
                }
                return hexstr.PadLeft(iLength, '0');

            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>
        /// 二进制转换为十进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string BinToDec(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    return Convert.ToInt64("0", 2).ToString();

                return Convert.ToInt64(x, 2).ToString();
            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>
        /// 二进制转换为十六进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string BinToHex(string x)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    x = "0";

                int values = 0;
                string Tmpstr = string.Empty; //hxh 2020-2-27 完善可以转换不定长度的二进制。以前只在4字节以内
                while (x.Length > 32)
                {
                    values = Convert.ToInt32(x.Substring(x.Length-32, 32), 2);//从右边开始转换
                    Tmpstr = Convert.ToString(values, 16).ToUpper().PadLeft(8, '0') + Tmpstr;
                    x = x.Remove(x.Length - 32);
                }
                values = Convert.ToInt32(x, 2);
                Tmpstr = Convert.ToString(values, 16).ToUpper().PadLeft(x.Length / 4, '0') + Tmpstr;
                return Tmpstr;
                //int values = Convert.ToInt32(x, 2);
                //return Convert.ToString(values, 16).ToUpper();
            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>        
        /// 二进制转换为十六进制 
        /// </summary>
        /// <param name="x">二进制字符串</param>
        /// <param name="bFillZero">是否补零成偶数位</param>
        /// <returns></returns>
        public static string BinToHex(string x, bool bFillZero)
        {
            try
            {
                if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                    x = "0";

                //int values =Convert.ToInt32(x, 2);
                //string str = Convert.ToString(values, 16).ToUpper();
                string str = BinToHex(x);//hxh 2020-2-27 完善可以转换不定长度的二进制。以前只在4字节以内

                if (bFillZero && str.Length % 2 != 0)
                    str = '0' + str;
                return str;
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// 二进制转换为十六进制，定长转换
        /// </summary>
        /// <param name="x">二进制字符串</param>
        /// <param name="iLength">二进制制字符长度</param>
        /// <returns>一定长度的二进制制字符串</returns>
        public static string BinToHex(string x, int iLength)
        {
            try
            {
                //if (string.IsNullOrEmpty(x)) //hxh 2018-8-22 如果传进来为空可以返回0
                //    x = "0";

                //long values = Convert.ToInt64(x, 2);
                //string str = Convert.ToString(values, 16);

                string str = BinToHex(x);//hxh 2020-2-27 完善可以转换不定长度的二进制。以前只在4字节以内
                if (iLength > 0 && str.Length > iLength)//增加长的截掉
                {
                    str = str.Substring(str.Length - iLength);
                }
                else
                    str = str.PadLeft(iLength, '0').ToUpper();

                return str;
            }
            catch (Exception ex)
            {
                return null;

            }
        }


        /// <summary>
        /// 将datetime转化为string "2011-12-31 01:01:01"或者"2011-12-31"
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="iDateOrDatetime">0为datetime即"2011-12-31 01:01:01"，1为date"2011-12-31"</param>
        /// <returns></returns>
        public static string DateTimeToString(DateTime dt, int iDatetimeOrDate)
        {
            if (iDatetimeOrDate == 0)
            {
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                return dt.ToString("yyyy-MM-dd");
            }

        }


        /// <summary>
        /// 将string转换为datetime 
        /// </summary>
        /// <param name="strDt">string严格要求为"2011-12-31 01:01:01"或者"2011-12-31"</param>
        /// <returns></returns>
        public static DateTime StringToDateTime(string strDt)
        {
            DateTime dt;
            if (strDt.Length <= 10)
            {
                dt = DateTime.ParseExact(strDt + " 00:00:00", "yyyy-MM-dd HH:mm:ss", null);
            }
            else
            {
                dt = DateTime.ParseExact(strDt, "yyyy-MM-dd HH:mm:ss", null);
            }
            return dt;
        }

        //以上两个补充修改     


        /// <summary>
        /// Object转字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string getString(object obj)
        {
            try
            {
                if (obj == null)
                {
                    return "";
                }
                else
                {
                    return obj.ToString();
                }
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 转换为Int32
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int getInt32(Object value) //GetInt32
        {
            try
            {
                if (value == null)
                {
                    return 0;
                }
                switch (value.GetType().ToString())
                {
                    case "System.String":
                        return Int32.Parse((string)value);
                    case "System.Int64":
                        return Int32.Parse(((long)value).ToString());
                    case "System.Int32":
                        return (int)value;
                    case "System.Double":
                        return (int)System.Math.Round((double)value, 0);
                    case "System.Boolean":
                        return 0;
                    case "System.DateTime":
                        return 0;
                    case "System.IO.MemoryStream"://getInt32
                        return 0;//MyConvert.ObjToInt32(MyConvert.getString(value));
                    case "System.Byte[]"://getInt32
                        return 0;//MyConvert.ObjToInt32(MyConvert.getString(value));
                    default:
                        return Convert.ToInt32(value);
                }
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 转换为double
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static double getDouble(Object value)
        {
            try
            {
                if (value == null)
                {
                    return 0.0;
                }
                switch (value.GetType().ToString())
                {
                    case "System.String":
                        return Double.Parse((string)value);
                    case "System.Int64":
                        return Double.Parse(((long)value).ToString());
                    case "System.Int32":
                        return Double.Parse(((int)value).ToString());
                    case "System.Boolean":
                        return 0.0;
                    case "System.Double":
                        return (Double)value; //(int)System.Math.Round((double)value, 0);
                    case "System.DateTime":
                        return 0.0;
                    case "System.IO.MemoryStream":
                        return 0;//MyConvert.ObjToInt32(MyConvert.getString(value));
                    case "System.Byte[]":
                        return 0;//MyConvert.ObjToInt32(MyConvert.getString(value));
                    default:
                        return Convert.ToDouble(value);
                }
            }
            catch
            {
                return 0.0;
            }
        }

        /// <summary>
        /// 去除无效的空逗号值
        /// </summary>
        /// <param name="table"></param>
        /// <param name="index"></param>
        public static void RemoveInvalidComma(ref Dictionary<string, Hashtable> table, string index)
        {
            try
            {
                if (table.ContainsKey(index))
                {
                    Hashtable hashvalue = table[index];
                    string strvalue = hashvalue["value"].ToString();
                    string[] values = strvalue.Split(',');
                    StringBuilder strb = new StringBuilder();
                    foreach (string value in values)
                    {
                        if (value.Trim() != "")
                        {
                            strb.Append(value + ",");
                        }
                    }
                    strvalue = strb.ToString();
                    if (strvalue.Length > 0 && strvalue.Substring(strvalue.Length - 1, 1) == ",")  //shaunwang 2014-9-16
                        strvalue = strvalue.Substring(0, strvalue.Length - 1);
                    hashvalue["value"] = strvalue;
                }
            }
            catch
            {
                return;
            }
        }

    }
}
